import sys
import pickle
import os
from PyQt5 import QtCore
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
import fun

class small_window(QMainWindow):
	def __init__(self):
		super().__init__()

class test_window(QMainWindow):

	#构造函数
	def __init__(self):
		super().__init__()
		self.init_test_kernal()
		self.initUI()


	#开始弹窗
	#生成弹窗判断读取进度还是重新开始
	def first_small_window(self):
		self.first_choice = -1
		reply = QMessageBox.question(self,'欢迎！',"是否读取进度？",  QMessageBox.Yes | 
			QMessageBox.No , QMessageBox.Yes)
		if reply == QMessageBox.Yes:
			self.first_choice = 0
		else:
			self.first_choice = 1
		

	#实例化测试核心对象
	def init_test_kernal(self):
		self.first_small_window()	#开始弹窗
		if self.first_choice == 0:
			self.my_test = fun.test_kernal()
			try:
				self.my_test.readfile()
			except OSError:
				QMessageBox.about(self, '错误',
				"         没有存档              ")
		elif self.first_choice == 1:
			self.my_test = fun.test_kernal()
		self.my_test.read_all_question()
		reply = QMessageBox.question(self,'请选择性别',"如果你是男性，请选择yes，否则选择no",  QMessageBox.Yes | 
			QMessageBox.No , QMessageBox.Yes)
		if reply == QMessageBox.Yes:
			self.my_test.gender = 'man'
		else:
			self.my_test.gender = 'woman'
		

	
	#初始化主窗体
	def initUI(self):
		#self.setWindowFlags(QtCore.Qt.WindowMinimizeButtonHint)
		self.end_test_question_showed = False
		self.show_status_box()							#生成作答状态文本框
		self.show_text_box()							#生成题目文本框
		self.check_question_not_answered_button()		#生成查看作答状态按钮
		self.choose_buttons()							#生成选项按钮
		self.trans_button()
		self.quit_button()								#生成退出按钮
		self.statusBar().showMessage('测试中......')		#生成状态栏
		self.jump_part()								#跳题部分
		self.setGeometry(300, 200, 1200, 600)			#设置窗体几何尺寸
		self.setWindowTitle('五大人格测试')    			#窗体标题
		self.show()


	#跳题功能
	def jump_part(self):
		#生成按钮
		self.show_now_status_button = QPushButton('当前题号:', self)
		self.show_now_status_button.move(20, 40)
		self.jump_button = QPushButton('跳转答题（J）', self)
		self.jump_button.setShortcut('j')
		self.jump_button.move(20, 80)
		self.jump_button.resize(140,40)
		#按钮动作
		self.jump_button.clicked.connect(self.show_jump_text_edit)
		#生成对话框
		self.jump_text_edit = QLineEdit(self)
		self.jump_text_edit.resize(30,30)
		self.jump_text_edit.move(130, 40)
		self.jump_text_edit.setFocusPolicy(QtCore.Qt.NoFocus)
		self.jump_text_edit.setText(str(self.my_test.number))
		

	#跳题输入数字并修改数字
	def show_jump_text_edit(self):
		text, ok = QInputDialog.getText(self, '跳题', 
			'你要跳转到第几题？（请输入一个1~240之间的数字：）')
		try:
			num = int(text)
			if num in list(range(1,241)):
				if ok:
					self.my_test.number = int(text)
					self.update_all()
			else:
				QMessageBox.about(self, '范围错误',
				"         指定的题号不在合法范围内              ")
		except ValueError:
			QMessageBox.about(self, '输入错误',
				"         不是数字！           ")



	#上一题、下一题
	def trans_button(self):
		self.button_up=QPushButton('上一题(u)',self)
		self.button_up.setStatusTip('上一题')
		self.button_up.setShortcut('u')
		self.button_up.clicked.connect(self.number_up)
		self.button_up.move(1050,50)

		self.button_down=QPushButton('下一题(d)',self)
		self.button_down.setStatusTip('下一题')
		self.button_down.setShortcut('d')
		self.button_down.clicked.connect(self.number_down)
		self.button_down.move(1050,100)


	#上一题的事件
	def number_up(self):
		if self.my_test.number in list(range(2,241)):
			self.my_test.number -= 1
			self.update_all()
		else:
			QMessageBox.about(self, '范围错误',
			"         没有上一题了！              ")

	#下一题的事件
	def number_down(self):
		if self.my_test.number in list(range(1,240)):
			self.my_test.number += 1
			self.update_all()
		else:
			QMessageBox.about(self, '范围错误',
			"         没有下一题了！              ")


	#出现0~4的选项按钮
	def choose_buttons(self):
		self.button=[0,1,2,3,4]

		self.button[0]=QPushButton('非常不符合(0)',self)
		self.button[0].setStatusTip('0分')
		self.button[0].setShortcut('0')
		self.button[1]=QPushButton('比较不符合(1)',self)
		self.button[1].setStatusTip('1分')
		self.button[1].setShortcut('1')
		self.button[2]=QPushButton('差不多(2)',self)
		self.button[2].setStatusTip('2分')
		self.button[2].setShortcut('2')
		self.button[3]=QPushButton('比较符合(3)',self)
		self.button[3].setStatusTip('3分')
		self.button[3].setShortcut('3')
		self.button[4]=QPushButton('非常符合(4)',self)
		self.button[4].setStatusTip('4分')
		self.button[4].setShortcut('4')

		for i in [0,1,2,3,4]:
			self.button[i].resize(150,100)
			self.button[i].move(200*i+150, 350)
		self.button[0].clicked.connect(lambda:self.setgrades(0))
		self.button[1].clicked.connect(lambda:self.setgrades(1))
		self.button[2].clicked.connect(lambda:self.setgrades(2))	
		self.button[3].clicked.connect(lambda:self.setgrades(3))
		self.button[4].clicked.connect(lambda:self.setgrades(4))


	#答题后保存答案
	def setgrades(self,num):
		self.my_test.grades[self.my_test.number-1] = num
		if self.my_test.number in self.my_test.question_not_answered:
			self.my_test.question_not_answered.remove(self.my_test.number)
		if self.my_test.number in list(range(1,240)):
			self.number_down()
		if self.my_test.number == 240:
			self.update_all()



	#用以显示题目的文本框
	def show_text_box(self):
		self.text_box = QTextEdit(self)
		self.text_box.setText(str(self.my_test.question_list[self.my_test.number]))
		self.text_box.setFocusPolicy(QtCore.Qt.NoFocus) 
		self.text_box.setGeometry(200,200,800,50)
		self.text_box.setAlignment(Qt.AlignCenter)


	#生成用以显示作答状态的文本框
	def show_status_box(self):
		self.status_box = QTextEdit(self)
		n = len(self.my_test.question_not_answered)
		n_= 240-n
		p = round((1-float(len(self.my_test.question_not_answered)/240))*100,2)
		if self.my_test.number in self.my_test.question_not_answered:
			status_string4 = "这道题你还没有作答"
		else:
			status_string4 = "这道题你已经作答过，之前的答案是: %s"%self.my_test.grades[int(self.my_test.number)-1]
		status_string1 = "已经作答了%s道题"%n_
		status_string2 = "还剩%s道题没有作答"%n
		status_string3 = "作答进度%s%%"%p
		self.status_box.setText(status_string1+'\n'+status_string2+'\n'+status_string3+'\n'+status_string4)
		self.status_box.setFocusPolicy(QtCore.Qt.NoFocus) 
		self.status_box.setGeometry(200,50,800,120)

	#查看没有作答的题目按钮
	def check_question_not_answered_button(self):
		self.button_check = QPushButton("查看未作答的题目",self)
		self.button_check.setGeometry(20,130,150,50)
		self.button_check.clicked.connect(self.check_question_not_answered)


	#查看没有作答的题目
	def check_question_not_answered(self):
		s1 = "以下题目未作答：\n"
		s2 = ""
		for i in self.my_test.question_not_answered:
			s2 += str(i)
			s2 += "."
		s = s1+s2
		self.status_box.setText(str(s))





	#更新状态
	def update_all(self):
		self.update_screen()
		self.update_status()
		self.end_test_question()


	#更新屏幕输出
	def update_screen(self):
		self.jump_text_edit.setText(str(self.my_test.number))
		self.text_box.setText(str(self.my_test.question_list[self.my_test.number]))
		self.text_box.setAlignment(Qt.AlignCenter)
		self.end_test_button()

	#更新作答状态文本框
	def update_status(self):
		n = len(self.my_test.question_not_answered)
		n_= 240-n
		p = round((1-float(len(self.my_test.question_not_answered)/240))*100,2)
		if self.my_test.number in self.my_test.question_not_answered:
			status_string4 = "这道题你还没有作答"
		else:
			status_string4 = "这道题你已经作答过，之前的答案是: %s"%self.my_test.grades[int(self.my_test.number)-1]
		status_string1 = "已经作答了%s道题"%n_
		status_string2 = "还剩%s道题没有作答"%n
		status_string3 = "作答进度%s%%"%p
		self.status_box.setText(status_string1+'\n'+status_string2+'\n'+status_string3+'\n'+status_string4)

	#出现"保存并退出"按钮
	def quit_button(self):
		self.button_quit = QPushButton('保存并退出(ESC)', self)
		self.button_quit.setShortcut('esc')
		self.button_quit.clicked.connect(self.closeEvent_mine)
		self.button_quit.resize(150,80)
		self.button_quit.move(950, 480)



	def closeEvent_mine(self):
		reply = QMessageBox.question(self, '退出提示',
			"确定要退出程序吗？", QMessageBox.Yes | 
			QMessageBox.No , QMessageBox.Yes)
		if reply == QMessageBox.Yes:
			self.my_test.savefile()
			self.close()



	#询问是否结束(只出现一次)
	def end_test_question(self):
		if self.end_test_question_showed == False:
			if self.my_test.question_not_answered == set():
				reply = QMessageBox.question(self, '作答结束',
				"你已答完\n是否结束答题并显示结果？", QMessageBox.Yes | 
				QMessageBox.No , QMessageBox.Yes)
				if reply == QMessageBox.Yes:
					self.end_test()
				self.end_test_question_showed = True



	#结束按钮
	def end_test_button(self):
		if self.my_test.question_not_answered == set():
			self.button_end = QPushButton('结束测试并显示结果(e)',self)
			self.button_end.setStatusTip('结束')
			self.button_end.setShortcut('e')
			self.button_end.clicked.connect(self.end_test)
			self.button_end.setGeometry(150,480,750,80)
			self.button_end.show()



	#结束测试
	def end_test(self):
		self.my_test.calculate()
		self.show_end()
		


	#展示得分
	def show_end(self):
		self.end_status = 0
		self.clear_screen()
		self.choose_points_buttons()
		self.update_end()
		self.show()
		self.load_in_file()


	#保存到文本文档里
	def load_in_file(self):
		my_dir = os.getcwd()
		file_name = os.path.join(my_dir,  "结果.txt")
		record_result = open(file_name,'w')
		s = [0,1,2,3,4]
		for i in [0,1,2,3,4]:
			s[i] = "------------------------------\n%s大项的得分为"%self.my_test.large_title[i]
			s[i]+=str(self.my_test.real_large_grades[i])
			s[i]+='\n'
		p = list(range(30))
		for i in list(range(30)):
			p[i] = "%s小项的得分为"%self.my_test.small_title[i]
			p[i]+=str(self.my_test.real_small_grades[i])
			p[i]+='\n'
		result_string = ''
		for i in list(range(5)):
			result_string+=s[i]
			for j in list(range(6)):
				result_string+=p[6*i+j]
		record_result.write(result_string)
		record_result.close()
		# os._exit(0)


	#选择展示哪个维度的按钮
	def choose_points_buttons(self):
		self.choose_button_end = [0,1,2,3,4]
		for i in [0,1,2,3,4]:
			self.choose_button_end[i] = QPushButton('new',self)

		self.choose_button_end[0].setText('展示N维度得分(0)')
		self.choose_button_end[0].setStatusTip('N')
		self.choose_button_end[0].setShortcut('0')
		self.choose_button_end[0].clicked.connect(lambda:self.show_points(0))

		self.choose_button_end[1].setText('展示E维度得分(1)')
		self.choose_button_end[1].setStatusTip('E')
		self.choose_button_end[1].setShortcut('1')
		self.choose_button_end[1].clicked.connect(lambda:self.show_points(1))

		self.choose_button_end[2].setText('展示O维度得分(2)')
		self.choose_button_end[2].setStatusTip('O')
		self.choose_button_end[2].setShortcut('2')
		self.choose_button_end[2].clicked.connect(lambda:self.show_points(2))

		self.choose_button_end[3].setText('展示A维度得分(3)')
		self.choose_button_end[3].setStatusTip('A')
		self.choose_button_end[3].setShortcut('3')
		self.choose_button_end[3].clicked.connect(lambda:self.show_points(3))

		self.choose_button_end[4].setText('展示C维度得分(4)')
		self.choose_button_end[4].setStatusTip('C')
		self.choose_button_end[4].setShortcut('4')
		self.choose_button_end[4].clicked.connect(lambda:self.show_points(4))

		for i in [0,1,2,3,4]:
			self.choose_button_end[i].resize(150,100)
			self.choose_button_end[i].move(200*i+150, 350)
			self.choose_button_end[i].show()




		#维度选择按钮的动作
	def show_points(self,num):
		self.end_status = num
		self.update_end()

	#更新结果
	def update_end(self):
		self.dimension_status()
		self.jump_text_edit.setText(str(self.end_status))
		
		#状态栏显示小项分
		small_points_string = ""
		for i in list(range(self.end_status*6,self.end_status*6+6)):
			small_points_string+="%s小项目得分="%self.my_test.small_title[i]
			small_points_string+=str(self.my_test.real_small_grades[i])
			small_points_string+='\n'
		self.status_box.setText(str(small_points_string))

		#题目栏显示大项分
		large_point_string = "%s大项得分="%self.my_test.large_title[self.end_status]
		large_point_string += str(self.my_test.real_large_grades[self.end_status])
		self.text_box.setText(str(large_point_string))



	#维度状态显示
	def dimension_status(self):
		self.jump_text_edit.setText(str(self.end_status))

		#清除没用的控件
	def clear_screen(self):
		for i in [0,1,2,3,4]:
			self.button[i].deleteLater()
		self.button_check.deleteLater()
		self.show_now_status_button.setText("当前维度")
		self.jump_button.deleteLater()
		self.button_up.deleteLater()
		self.button_down.deleteLater()
		self.button_quit.deleteLater()
		self.button_end.deleteLater()
		self.statusBar().showMessage('查看结果')



if __name__ == '__main__':
	app = QApplication(sys.argv)
	ex = test_window()
	sys.exit(app.exec_())